import sqlite3
import datetime
import sys
import os

# 模拟程序中的insert_trade_record函数实现
def insert_trade_record(product_name, direction, offset, volume, price, reason, timestamp=None):
    try:
        # 如果没有提供时间戳，使用当前时间
        if timestamp is None:
            timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        # 连接到SQLite数据库
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 参数化插入SQL语句
        insert_sql = '''
            INSERT INTO trade_records (
                product_name, direction, offset, volume, price, reason, timestamp, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        '''
        
        # 执行插入
        cursor.execute(insert_sql, (
            product_name, direction, offset, volume, price, reason, timestamp, timestamp
        ))
        
        # 提交事务
        conn.commit()
        
        print(f"模拟插入成功: {product_name}, {direction}, {offset}, {volume}, {price}, {reason}, {timestamp}")
        return True
        
    except Exception as e:
        print(f"模拟插入失败: {str(e)}")
        # 在实际程序中可能有日志记录，但这里直接打印
        # logging.error(f"插入交易记录失败: {str(e)}")
        return False
    finally:
        if conn:
            conn.close()

# 从实际程序文件中提取insert_trade_record函数的实际实现
def get_actual_insert_function():
    try:
        # 查找主程序文件
        main_files = [f for f in os.listdir('.') if f.startswith('auto_stp10') and f.endswith('.py')]
        
        print("\n正在查找实际的insert_trade_record函数实现...")
        
        for main_file in main_files:
            try:
                with open(main_file, 'r', encoding='utf-8', errors='ignore') as f:
                    content = f.read()
                    
                    if 'def insert_trade_record' in content:
                        print(f"在文件 {main_file} 中找到函数定义")
                        
                        # 提取函数定义
                        start_index = content.find('def insert_trade_record')
                        end_index = content.find('def ', start_index + 1) 
                        if end_index == -1:
                            end_index = len(content)
                        
                        function_code = content[start_index:end_index]
                        print(f"函数定义长度: {len(function_code)} 字符")
                        
                        # 检查关键代码
                        if 'console.print' in function_code:
                            print("  ✓ 包含console.print输出")
                        if 'logging.error' in function_code:
                            print("  ✓ 包含logging.error日志")
                        if 'commit()' in function_code:
                            print("  ✓ 包含commit()提交")
                        if 'rollback()' in function_code:
                            print("  ✓ 包含rollback()回滚")
                        
                        # 只检查第一个找到的函数
                        return main_file
            except Exception as e:
                print(f"读取文件 {main_file} 时出错: {str(e)}")
                continue
        
        print("未找到insert_trade_record函数定义")
        return None
    except Exception as e:
        print(f"查找过程中出错: {str(e)}")
        return None

# 模拟程序调用流程
def simulate_program_flow():
    print("=== 模拟程序调用流程测试 ===")
    
    # 1. 首先测试基本插入
    print("\n1. 测试基本插入功能:")
    basic_result = insert_trade_record(
        product_name="TEST.symbol",
        direction="BUY",
        offset="OPEN",
        volume=2.0,
        price=5000.0,
        reason="测试插入"
    )
    print(f"基本插入测试结果: {'成功' if basic_result else '失败'}")
    
    # 2. 模拟9月16日的交易数据
    print("\n2. 模拟9月16日的交易数据:")
    sep16_timestamp = "2025-09-16 10:30:00"
    sep16_result = insert_trade_record(
        product_name="DCE.jm2601",
        direction="BUY",
        offset="OPEN",
        volume=3.0,
        price=1149.5,
        reason="开多仓",
        timestamp=sep16_timestamp
    )
    print(f"9月16日数据插入结果: {'成功' if sep16_result else '失败'}")
    
    # 3. 检查是否真的插入了记录
    print("\n3. 验证插入结果:")
    try:
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 查询最近插入的记录
        cursor.execute("SELECT * FROM trade_records ORDER BY id DESC LIMIT 2")
        latest_records = cursor.fetchall()
        
        print(f"最近的2条记录:")
        for record in latest_records:
            print(f"  {record}")
            
        # 统计总记录数
        cursor.execute("SELECT COUNT(*) FROM trade_records")
        total_count = cursor.fetchone()[0]
        print(f"总记录数: {total_count}")
        
    except Exception as e:
        print(f"验证过程中出错: {str(e)}")
    finally:
        if conn:
            conn.close()
    
    # 4. 查找实际的函数实现
    actual_file = get_actual_insert_function()
    
    print("\n=== 问题分析总结 ===")
    print("基于测试结果，以下是可能的问题原因:")
    print("1. 数据库本身完全正常，测试插入功能正常工作")
    print("2. 程序可能在调用insert_trade_record函数时出现了逻辑问题")
    print("3. 可能存在条件判断，导致某些交易没有被记录")
    print("4. 可能是异常处理不当，捕获了错误但没有正确记录")
    
    if actual_file:
        print(f"建议检查文件: {actual_file} 中的insert_trade_record函数实现")
    else:
        print("请检查程序中调用insert_trade_record的相关代码")

if __name__ == "__main__":
    simulate_program_flow()